package com.sample.myweb;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

/**
 * 与H5通信,
 *
 */
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "wangwiejun java ";
    public static final String LOCAL_URL = "file:///android_asset/my.html";
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true); // 启动js
        // 注入对象后，前端可以window.injectedObject.methodId
        webView.addJavascriptInterface(new JsObject(), "injectedObject");
        webView.loadUrl(LOCAL_URL);
    }

    class JsObject {
        @JavascriptInterface
        public void post(String cmd, String param) {
            Log.i(TAG, "cmd = " + cmd + ", param = " + param);
            // javascript:dj.callback({"title":"cancel","id":"cancel","callbackname":"djapi_callback_1636628537832_2261"})
//            final String script = "javascript:dj.callback('title')";// 也可以直接传一个字符串
//            final String script = "javascript:dj.callback({'title':'cancel'})";
            String response = "{'title':'cancel'}";
            final String script = "javascript:" + "dj.callback" + "(" + response + ")";
            runOnUiThread(new Runnable() { // 必须执行在 UI Thread (JsBrigd同一个线程)
                @Override
                public void run() {
                    // java 调用js, 一定是在ui thread, 第二前端告诉你对象以及方法
                    // javascript:dj.callback(xxxx)
                    webView.evaluateJavascript(script, null);
                }
            });

        }
    }
}